<template>
  <div>
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-position="top"
      label-width="80px"
    >
      <el-form-item v-if="rejectUser" label="驳回至">
        <el-tag>{{ rejectUser }}</el-tag>
      </el-form-item>
      <el-form-item label="驳回意见" prop="remarks">
        <el-input
          v-model.trim="formData.remarks"
          type="textarea"
          :rows="3"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-row justify="end">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { defineEmits, reactive, ref, defineProps } from "vue";
import { postFlowReject } from "/@/api/quality";

import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";

const router = useRouter();
const route = useRoute();
const formRef = ref<HTMLFormElement | null>(null) as any;
const emit = defineEmits(["update:dialogVisible"]);
const props = defineProps({
  taskId: {
    type: String,
    default: ""
  },
  recordId: {
    type: Number
  },
  rejectUser: {
    type: String,
    default: ""
  }
});

let formData = reactive({
  remarks: ""
});

const formRules = {
  remarks: {
    required: true,
    message: "请输入驳回意见",
    trigger: "change"
  }
};

const handleSubmit = async () => {
  try {
    const isValid = await new Promise(resolve =>
      formRef.value.validate(resolve)
    );
    if (!isValid) return;

    const { nodeDefId, instanceId } = route.query;
    const params = {
      formRejectMap: {
        nodeId: nodeDefId,
        procInstId: instanceId,
        taskId: props.taskId,
        opinion: `#e#驳回意见：${formData.remarks}`,
        recordId: props.recordId
      }
    };
    const { code } = await postFlowReject(params);
    if (code === 200) {
      NotifMessage.success("驳回成功");
      handleCancel();
      // router.replace("/acceptance/arrival");
      handleBack();
    }
  } catch (err) {
    console.log(err);
  }
};

const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/quality/inspection", replace: true });
  }
};

const handleCancel = () => {
  emit("update:dialogVisible", false);
};
</script>
